package com.guigu.userservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.JwtUtils;
import com.guigu.common.utils.MD5;
import com.guigu.common.utils.R;
import com.guigu.common.utils.ResultCode;
import com.guigu.userservice.entity.User;
import com.guigu.userservice.service.UserService;
import com.guigu.userservice.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表（平台买卖双方用户） 前端控制器
 * </p>
 *
 * @author zcy
 * @since 2025-09-27
 */
@RequestMapping("/user/usercon")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserController userController;

    @PutMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody User user){
        user.setUpdateTime(LocalDateTime.now());
        boolean b = userService.updateById(user);
        if (b) {
            return R.ok().message("更新成功");
        }else return R.error().message("更新失败");
    }

    @GetMapping("/ ")
    public List<User> queryAllUser(){
        return userService.list();
    }

    /**
     * 根据条件查询用户
     */
    @PostMapping("/queryUserByVo/{pageNum}/{pageSize}")
    public PageInfo<User> queryUserByVo(@RequestBody UserVo vo,
                                        @PathVariable("pageNum") Integer pageNum,
                                        @PathVariable("pageSize") Integer pageSize
                                    ){
        return userService.queryUserByVo(vo, pageNum, pageSize);
    }

    /**
     * 根据id查询用户
     */
    @GetMapping("/queryUserById/{id}")
    public User queryUserById(@PathVariable("id") Integer id){
        return userService.getById(id);
    }

    /**
     * 我要卖-根据id查询用户
     */
    @GetMapping("/selectUserById/{id}")
    public User selectUserById(@PathVariable("id") Long id){
        return userService.getById(id);
    }
    /**
     * 我要卖-根据用户id修改用户状态
     */
    @PutMapping("/updateUserStatus/{id}")
    public User updateUserStatus(@PathVariable("id") Long id){
        User byId = userService.getById(id);
        byId.setUserType(2);
        boolean b = userService.updateById(byId);
        return byId;
    }

    /**
     *
     */
    @PutMapping("/updateStatus/{id}/{status}")
    public R updateStatus(@PathVariable("id") Integer id,
                          @PathVariable("status") Integer status){


        return userService.updateUserStatus(id, status);
    }

    /**
     * 用户登录
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("/login/{phone}/{password}")
    public R login(@PathVariable("phone") String phone,
                   @PathVariable("password") String password){
        return userService.loginUser(phone, password);
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @return
     */
    @PostMapping("/addUser")
    public R addUser(@RequestBody User user){
        return userService.addUser(user);
    }


    /**
     * 前台-用户注册
     * @param user 用户信息
     * @return
     */
    @PostMapping("/PCaddUser")
    public R PCaddUser(@RequestBody User user){
        //根据手机号查询该手机号是否注册过
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone",user.getPhone());
        User dx = userService.getOne(userQueryWrapper);
        if (dx!=null){
            return R.error().message("该手机号已注册");
        }

        //修改用户启动状态
        user.setStatus(1);
        // 默认注册为买家
        user.setUserType(0);
        //注册时间
        user.setRegisterTime(LocalDateTime.now());
        //创建时间
        user.setCreateTime(LocalDateTime.now());
        //更新时间
        user.setUpdateTime(LocalDateTime.now());

        //加密密码
        user.setPassword(MD5.encrypt(user.getPassword()));

        //注册
        boolean save = userService.save(user);

        return R.ok().data("user",user);
    }

    /**
     * 前台-用户登录
     */
    @PostMapping("/PCloginUser")
    public R PCloginUser(@RequestBody User user){
        return userService.PCloginUser(user);
    }


    /**
     * 根据登录的返回的牌获取用户名
     */
    @PostMapping("/selectUserNameByJwtToken")
    public R selectUserNameByJwtToken(HttpServletRequest request){
        String userNameByJwtToken = JwtUtils.getUserNameByJwtToken(request);
        return  R.ok().data("userNameByJwtToken",userNameByJwtToken);
    }


    /**
     * 根据登录的返回的牌获取用户id
     */
    @PostMapping("/getLoginUserInfoByToken")
    public R getLoginUserInfoByToken(HttpServletRequest request){
        String userIDByJwtToken = JwtUtils.getUserIDByJwtToken(request);
        return  R.ok().data("userIDByJwtToken",userIDByJwtToken);
    }


    /**
     * 前台-根据用户id返回用户对象
     */
    @GetMapping("/getUserinfoById/{id}")
    public R getUserinfoById(@PathVariable("id") Integer id){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id",id);
        userQueryWrapper.eq("status",1);

        User user = userService.getOne(userQueryWrapper);

        return R.ok().data("user",user);
    }

    /**
     * 前台-发送验证码
     */
    @GetMapping("/sendCode")
    public R sendCode(){
        Integer code = userService.sendCode();
        return R.ok().data("code",code);
    }


    /**
     * 前台-根据传递的买家id查询用户对象
     */
    @GetMapping("/selectUserToBuyerId/{id}")
    public R selectUserToBuyerId(@PathVariable("id") Integer id){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id",id);

        User user = userService.getOne(userQueryWrapper);

        return R.ok().data("user",user);
    }

    /**
     * 前台-根据传递的卖家id查询用户对象
     */
    @GetMapping("/selectUserToSellerId/{id}")
    public R selectUserToSellerId(@PathVariable("id") Integer id){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id",id);

        User user = userService.getOne(userQueryWrapper);

        return R.ok().data("user",user);
    }

    /**
     * 前台-修改手机号
     */
    @PutMapping("/editUserPhone")
    public R editUserPhone(@RequestBody User user){
        boolean b = userService.updateById(user);
        if (b==true)
           return R.ok().code(20000).message("修改成功").data("success", true);
        return R.error().code(20001).message("修改失败").data("success", false);
    }

    //根据业务员查询设备信息-》用设备id查询-》order-》/purchase_demand求购表的设备，
    // 再获取买家和卖家的信息，之后再去用户表获取数据
    //最后返回的User
    @GetMapping("/queryUserList/{businessmanId}")
    public List<User> queryUserList(@PathVariable("businessmanId") Long businessmanId) {
        return userService.getUniqueUserDetails(businessmanId);
    }

}
